<?php
// WARNING: this will work only in PHP5
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 * @date       2009-02-25
 */
class Accmontreal_tpl {

    protected $menu_file_name = 'menu';
    protected $menu_links = array();
    
    public function __construct($name='menu',$setlang=false,$id=false) {
        global $conf,$ID;
        $this->menu_file_name = ':'.$name;
        if($setlang){
            if(!$id) $id = $ID;
            $this->set_lang_from_id($id);
            $this->menu_file_name = ':'.$conf['lang'].$this->menu_file_name;
        }
        $this->menu_links = $this->getmenulinks($this->menu_file_name);
    }
    

    /**
     * Parse a sitemap style page [nested lists up to 2 levels] into an array
     */
    protected function getmenulinks($menufilename = false){      	
      	if(!$menufilename) $menufilename = $this->menu_file_name;
    	if (@file_exists(wikiFN($menufilename))){
            $ins = p_cached_instructions(wikiFN($menufilename));
    		$mymenu  = array();
    		$mylevel = 0;
            foreach ($ins as $in){
    			if ($in[0] == 'listu_open') {
    				$mylevel = $mylevel + 1;
    				if ($mylevel <= 2) $mysubmenu = array();
    			} else if ($in[0] == 'listu_close') {
    				if ($mylevel == 2) $mymenu[count($mymenu)-1]['submenu'] = $mysubmenu;
    				$mylevel = $mylevel - 1;
    			} else if ($in[0] == 'internallink' && $mylevel > 0) {
    				list($id, $hash) = explode('#', $in[1][0], 2);
    				resolve_pageid(getNS($ID), $id, $exists);
    				$title = hsc($in[1][1]);
    				if (!$title) $title = hsc(p_get_first_heading($id));
    				if (!$title) $title = hsc(ucwords(noNS($id)));
    				if ($mylevel == 1) {
    					$mymenu[] = array(
    						'id' => $id,
    						'title' => $title,
    						);
    				} else if ($mylevel == 2) {
    					$mysubmenu[] = array(
    						'id' => $id,
    						'title' => $title,
    						);
    				}
    			}
    		}
    	} else {
    		return false;
    	}
    	return $mymenu;
    }
    
    
    /**
     *
     */
    protected function menu_set_status(&$menuarray){
    	global $ID;
    	$id = $ID;
    	resolve_pageid(':',$ID,$exists);
    	$hasactive = false;
    	foreach($menuarray as $i => $item){
    	    $active = false;
	        $id2 = $item['id'];
	        resolve_pageid(':',$id2,$exists);
	        if($id2 == $id) $active = true;
    	    if(is_array($item['submenu'])){
    	        $submenu = $item['submenu'];
    	        //echo '<pre>1:'.$id2."\n$id";print_r($submenu);echo '</pre>';
    	        $active = $this->menu_set_status($submenu) || $active;
    	        //echo '<pre>2:'.$id2."\n$id";print_r($submenu);echo '</pre>';
    	        $menuarray[$i]['submenu'] = $submenu;
    	    }
    	    //if(!$active){
    	        //TODO: may want to check if page is under a NS
    	    //}
    	    if($active) $hasactive = true;
    	    $menuarray[$i]['active'] = $active;
    	}
    	return $hasactive;
    }    
    
    /**
     * check that $ID is under getNS($id);
     */
    protected function is_under($id2){
    	global $ID;
		$isIn = false;
    	//$ns = getNS($ID);
		$ns2 = getNS($id2);
		if(strpos($ns2,':',1)>0){
		    if(strpos($ID,$ns2.':') === 0) $isIn = true;
		} else {
		    if(strpos($ID,$id2) === 0) $isIn = true;
		}
		return $isIn;
    }

    /**
     * Display the topbar
     */
    public function show_topbar($maxlevel=2,$menu_links=false,$level=1){
    	global $ID;
      	$out = '';
    	$mysubmenu = false;
    	if(!$menu_links) $menu_links = $this->menu_links;
    	$oneactive = $this->menu_set_status($menu_links);
    	
    	$hasactive = false;
    	foreach ($menu_links as $menuitem){
    		$id    = $menuitem['id'];
    		$title = $menuitem['title'];
    		if($oneactive) $isIn = $menuitem['active']; 
    		else $isIn = $this->is_under($id);
    		$myclass = "tablink".$level;
    		if ($isIn && !$hasactive) {
    		    $hasactive = true; 
    		    $myclass = "active".$myclass;
                if (isset($menuitem['submenu'])) $mysubmenu = $menuitem['submenu'];
    		}
        	$out .= '<a href="'.wl($id).'" class="'.$myclass.'">'.$title.'</a>';
    	}
        $myclass = "tabs".$level;
    	echo '<div class="'.$myclass.'">'.$out.'</div>';
    	if (is_array($mysubmenu) && $level<$maxlevel) 
    	    $this->show_topbar($maxlevel,$mysubmenu,$level+1);
    }
    
    /**
     * Display the foot menu
     */
    public function show_menu_foot() {
    	$mymenu = $this->menu_links;
    	$out = '<div class="foot_menu"><div><ul>';
    	foreach ($mymenu as $menuitem){
    		$id    = $menuitem['id'];
    		if ($id != 'en:home' && $id != 'fr:home') {
    		$title = $menuitem['title'];
    		$wl   = wl($id);
    		$out .= '<li><a href="'.$wl.'" class="'.$myclass.'">'.$title.'</a>';
    		if (isset($menuitem['submenu'])) {
    			$out .= '<ul>';
    			foreach ($menuitem['submenu'] as $menuitem2){
    				$id    = $menuitem2['id'];
    				$wl2   = wl($id);
    				//if ($wl != $wl2) {
    					$title = $menuitem2['title'];
    					$out .= '<li><a href="'.wl($id).'" class="'.$myclass.'">'.$title.'</a></li>';
    				//}
    			}
    			$out .= '</ul>';
    		}
    		$out .= '</li>';
    		}
    	}
    	$out .= '</ul></div></div>';
    	echo $out;
    }


    /**
     *  
     */
     function get_lang_from_id($id) {
        $ns = getNS($id);
        $top_ns = '';
        while ($ns) {
            $top_ns = $ns;
            $ns = getNS($ns);
        }
        if ($top_ns != 'en') return 'fr';
        return 'en';
    }
    
    function set_id_from_lang() {
        return false;
    }
    
    function echo_lang_switch_link($id,$keep_get_attr=true) {
        global $conf;
        $attrs = '';
        if($keep_get_attr){
            $attrs = $_GET;
            if(isset($attrs['id'])) unset($attrs['id']);
        }
        if ($conf['lang'] != 'en') {
            $id = preg_replace('/^fr(:.*)/','en$1',$id);
            //$id2 = explode(':',$id);
            //$id2[0] = 'fr';
            //$id = implode(':',$id2);
            tpl_link(wl($id,$attrs),'English',"alt='$id'");
        } else {
            $id = preg_replace('/^en(:.*)/','fr$1',$id);
            //$id2 = explode(':',$id);
            //$id2[0] = 'fr';
            //$id = implode(':',$id2);
            tpl_link(wl($id,$attrs),'Français',"alt='$id'");
        }
    }
    
    function set_lang_from_id($id) {
        global $conf,$lang;
        $lang2 = $this->get_lang_from_id($id);
        if ($lang2 != $conf['lang']) {
            $conf['lang'] = $lang2;
            @include(DOKU_INC.'inc/lang/'.$conf['lang'].'/lang.php');
        }
    } 
     
     
     /**
     * Hierarchical breadcrumbs
     *
     * This code was suggested as replacement for the usual breadcrumbs.
     * It only makes sense with a deep site structure.
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     * @author Nigel McNie <oracle.shinoda@gmail.com>
     * @author Sean Coates <sean@caedmon.net>
     * @author Stephane Chamberland <stephane.chamberland@gmail.com> : skip startpage for multi-lang wiki
     * @link   http://wiki.splitbrain.org/wiki:tipsandtricks:hierarchicalbreadcrumbs
     * @todo   May behave strangely in RTL languages
     */
    function tpl_youarehere2($sep=' &raquo; '){
      global $conf;
      global $ID;
      global $lang;
    
      // check if enabled
      if(!$conf['youarehere']) return false;
    
      $parts = explode(':', $ID);
      $count = count($parts);
    
      if ($count < 2 || $parts[1] == strtolower($conf['start'])) return false;
    
      echo $lang['youarehere'].': ';
    
      // always print the startpage
      //$title = p_get_first_heading($conf['start']);
      //if(!$title) $title = $conf['start'];
      //tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
    
      // print intermediate namespace links
      $part = '';
      for($i=0; $i<$count - 1; $i++){
        $part .= $parts[$i].':';
        $page = $part;
        resolve_pageid('',$page,$exists);
        if ($page == $conf['start']) continue; // Skip startpage 
        if ($page == $conf['lang'].':'.$conf['start']) {
              if (!$lang['home']) {
                  $lang['home'] = ($conf['lang']=='fr') ? 'Accueil' : 'Home';
              } 
              tpl_link(wl($page),$lang['home'],'title="Home"');
            continue;
        }    
        // output
        if ($i > 0) echo $sep;
        if($exists){
          $title = p_get_first_heading($page);
          if(!$title) $title = $parts[$i];
          tpl_link(wl($page),hsc($title),'title="'.$page.'"');
        }else{
          tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2"');
        }
      }
    
      // print current page, skipping start page, skipping for namespace index
      if(isset($page) && $page==$part.$parts[$i]) return;
      $page = $part.$parts[$i];
      if($page == $conf['start']) return;
      echo $sep;
      if(@file_exists(wikiFN($page))){
        $title = p_get_first_heading($page);
        if(!$title) $title = $parts[$i];
        tpl_link(wl($page),hsc($title),'title="'.$page.'"');
      }else{
        tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2"');
      }
      return true;
    }


}